const Controller = require('egg').Controller;

class LostAndFoundController extends Controller {
    // 创建失物招领物品
    async create() {
        const { ctx, service } = this;

        try {
            // 参数验证
            const rules = {
                title: { type: 'string', required: true, max: 100 },
                description: { type: 'string', required: true },
                category: { type: 'string', required: true, max: 50 },
                contact_info: { type: 'string', required: true, max: 100 }
            };
            ctx.validate(rules);

            const itemData = ctx.request.body;

            // 从token中获取用户ID
            const token = ctx.request.header.token;
            if (!token) {
                throw new Error('请先登录');
            }

            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
            if (decode.type !== 'user') {
                throw new Error('无权限操作');
            }

            // 设置用户ID
            itemData.user_id = decode.user_id;

            const result = await service.lostAndFound.create(itemData);

            ctx.body = {
                code: 0,
                data: result,
                msg: '创建成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '创建失败'
            };
        }
    }

    // 获取失物招领列表
    async list() {
        const { ctx, service } = this;

        try {
            const query = ctx.query;

            // 不再进行严格验证，让 Service 层处理参数转换
            const result = await service.lostAndFound.getItems(query);

            ctx.body = {
                code: 0,
                data: result,
                msg: '获取成功'
            };
        } catch (error) {
            console.error('获取列表失败:', error);
            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取列表失败'
            };
        }
    }

    // 获取简单列表（不关联用户信息）
    async listSimple() {
        const { ctx, service } = this;

        try {
            const query = ctx.query;
            const result = await service.lostAndFound.getItemsSimple(query);

            ctx.body = {
                code: 0,
                data: result,
                msg: '获取成功'
            };
        } catch (error) {
            console.error('获取简单列表失败:', error);
            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取列表失败'
            };
        }
    }

    // 获取我的物品
    async myItems() {
        const { ctx, service } = this;

        try {
            // 从token中获取用户ID
            const token = ctx.request.header.token;
            if (!token) {
                throw new Error('请先登录');
            }

            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
            if (decode.type !== 'user') {
                throw new Error('无权限访问');
            }

            const query = ctx.query;
            const result = await service.lostAndFound.getUserItems(decode.user_id, query);

            ctx.body = {
                code: 0,
                data: result,
                msg: '获取成功'
            };
        } catch (error) {
            console.error('获取我的物品失败:', error);
            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取我的物品失败'
            };
        }
    }

    // 获取物品详情
    async detail() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;

            // 验证ID参数
            const rules = {
                id: { type: 'id', required: true }
            };
            ctx.validate(rules, ctx.params);

            const item = await service.lostAndFound.getItemById(id);

            ctx.body = {
                code: 0,
                data: item,
                msg: '获取成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取物品详情失败'
            };
        }
    }

    // 更新物品信息
    async update() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;
            const updateData = ctx.request.body;

            // 验证路径参数
            const paramRules = {
                id: { type: 'id', required: true }
            };
            ctx.validate(paramRules, ctx.params);

            // 验证body参数
            const bodyRules = {
                title: { type: 'string', required: false, max: 100 },
                description: { type: 'string', required: false },
                category: { type: 'string', required: false, max: 50 },
                contact_info: { type: 'string', required: false, max: 100 }
            };
            ctx.validate(bodyRules);

            // 从token中获取用户ID
            const token = ctx.request.header.token;
            if (!token) {
                throw new Error('请先登录');
            }

            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
            if (decode.type !== 'user') {
                throw new Error('无权限操作');
            }

            // 检查物品是否存在且属于当前用户
            const item = await ctx.model.LostAndFound.findByPk(id);
            if (!item) {
                throw new Error('物品不存在');
            }

            if (item.user_id !== decode.user_id) {
                throw new Error('只能修改自己发布的物品');
            }

            const result = await service.lostAndFound.updateItem(id, updateData);

            ctx.body = {
                code: 0,
                data: result,
                msg: '更新成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '更新物品信息失败'
            };
        }
    }

    // 更新物品状态
    async updateStatus() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;
            const { status } = ctx.request.body;

            // 验证路径参数
            const paramRules = {
                id: { type: 'id', required: true }
            };
            ctx.validate(paramRules, ctx.params);

            // 验证body参数
            const bodyRules = {
                status: { type: 'number', required: true, min: 0, max: 2 }
            };
            ctx.validate(bodyRules);

            // 从token中获取用户ID
            const token = ctx.request.header.token;
            if (!token) {
                throw new Error('请先登录');
            }

            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
            if (decode.type !== 'user') {
                throw new Error('无权限操作');
            }

            // 检查物品是否存在且属于当前用户
            const item = await ctx.model.LostAndFound.findByPk(id);
            if (!item) {
                throw new Error('物品不存在');
            }

            if (item.user_id !== decode.user_id) {
                throw new Error('只能修改自己发布的物品');
            }

            const result = await service.lostAndFound.updateItemStatus(id, status);

            ctx.body = {
                code: 0,
                data: result,
                msg: '状态更新成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '更新状态失败'
            };
        }
    }

    // 删除物品
    async delete() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;

            // 验证ID参数
            const rules = {
                id: { type: 'id', required: true }
            };
            ctx.validate(rules, ctx.params);

            // 从token中获取用户ID
            const token = ctx.request.header.token;
            if (!token) {
                throw new Error('请先登录');
            }

            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
            if (decode.type !== 'user') {
                throw new Error('无权限操作');
            }

            // 检查物品是否存在且属于当前用户
            const item = await ctx.model.LostAndFound.findByPk(id);
            if (!item) {
                throw new Error('物品不存在');
            }

            if (item.user_id !== decode.user_id) {
                throw new Error('只能删除自己发布的物品');
            }

            await service.lostAndFound.deleteItem(id);

            ctx.body = {
                code: 0,
                data: null,
                msg: '删除成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '删除物品失败'
            };
        }
    }
}

module.exports = LostAndFoundController;